#!/usr/bin/env python 
#-*- Coding: UTF-8 -*-

import socket
import struct
import sys
import time
import SocketServer
from threading import *
import binascii, re
from array import *
from datetime import datetime
#from event import event

match_pub = re.compile("PUBLISH\s(.+?)\s(.+?)\s(\d+)") # PUBLISH NAME IP PORT
match_off = re.compile("OFFLINE")
match_alive = re.compile("ALIVE")


published = {}
#listen_ip = "192.168.0.1"
listen_port = 5542
listen_addr = ("0.0.0.0",listen_port)
alisten_addr = ("0.0.0.0",listen_port +1) #Alive

socket.setdefaulttimeout(5)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind(listen_addr)

def runalive():
    global published,sock
    while 1:
        temp = {}
        time.sleep(10)
        for i in published:
            print "ALIVE",i,"?"
            try:
                sock.sendto("ALIVE",i)
                if time.time() - float(published[i]['last_seen']) < 60:
                    #if not responded to ALIVE over 1 minute, remove
                    temp[i] = published[i]
            except socket.timeout,e:
                pass
            except:
                temp[i] = published [i] # just in case some unknown error
        published = temp
    
t = Thread(target=runalive, name="alivethread")
t.setDaemon(True)
t.start()

while 1:
    try:
        data,addr =  sock.recvfrom(1024)
        print "Received:",addr,">",data
        m = match_pub.match(data)
        if m :
            print "Name:",m.group(1),"Addr: %s:%s"%(m.group(2),m.group(3))
            published[addr] = {}
            published[addr]['id'] = m.group(1)
            published[addr]['last_seen'] = time.time()
            sock.sendto("OK PUBLISH",addr)
            print published
            
        m = match_alive.match(data)
        if m:
            published[addr]['last_seen'] = time.time()
            
        print "- - - - - - - - - - - - - - - - - - -"
    except KeyboardInterrupt,e:
        break
    except socket.timeout,e:
        pass #print "timeout"
    

